package com.trainoo.mina.server;

import com.trainoo.mina.handler.MyServerHandler;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;

/**
 * 配置Socket
 */
@Configuration
public class MinaConfig {

    private int PORT = 22222;

    /**
     * 拦截器
     */
    @Bean
    public IoHandler ioHandlerG() {
        return new MyServerHandler();
    }

    /**
     * 定义监听端口
     */
    @Bean
    public InetSocketAddress inetSocketAddress() {
        return new InetSocketAddress(PORT);
    }

    @Bean
    public IoAcceptor ioAcceptorG() throws Exception {
        IoAcceptor acceptor = new NioSocketAcceptor();
        // 增加编码过滤器，统一编码UTF-8、TextLineCodecFactory,接收一行消息
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
        // 设置服务端逻辑处理器
        acceptor.setHandler(ioHandlerG());
        // 设置读缓存大小
        acceptor.getSessionConfig().setReadBufferSize(2048);
        // 设置指定类型的空闲时间，空闲时间超过这个值将触发sessionIdle方法
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
        // 绑定端口
        acceptor.setDefaultLocalAddress(inetSocketAddress());
        acceptor.bind();

        System.out.println("Mina Server is Listen on:" + PORT);
        return acceptor;
    }
}
